<?php

namespace addons\shopro\controller\user;

use addons\shopro\traits\CouponSend;
use app\admin\model\shopro\user\User as UserModel;
use think\helper\Str;
use addons\shopro\controller\Common;
use app\admin\model\shopro\Coupon as ShoproCoupon;
use app\admin\model\shopro\user\Coupon as UserCouponModel;

class Coupon extends Common
{
    use CouponSend;

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 赠送优惠券
     * @ApiMethod (POST)
     * @param int $user_coupon_id 优惠券Id
     * @param string $mobile 手机号
     * @return bool
     */
    public function present()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $userCouponId = $this->request->param('user_coupon_id');

       

        $mobile = $this->request->param('mobile');
        $presentUserInfo = UserModel::where('mobile', $mobile)->find();
           

       if (empty($presentUserInfo)) {
           $this->error("用户不存在");
       }
        $userCoupon = UserCouponModel::get(['id'=>$userCouponId]);

        


        if (empty($userCoupon)) {
            $this->error("优惠券不存在");
        }
        $coupon = ShoproCoupon::where('id', $userCoupon->coupon_id)->find();      // 正常的可以展示的优惠券
           

        if ($coupon->setUseEndTimeAttr($coupon->use_end_time, $coupon) <=  time()) {
            $this->error("优惠券已过期");
        }
        $res['user_id'] = $presentUserInfo['id'];
        
        // echo "<pre>";
        // print_r($res['user_id']);die;

        UserCouponModel::where('id', $userCouponId)->update($res);

        $this->presentCoupon($presentUserInfo, $userCoupon);

        $this->success(__('ok'),['msg' => '恭喜此券赠送成功']);
    }

    /**
     * 优惠券升级
     * @ApiMethod (POST)
     * @param int $user_coupon_id 优惠券Id
     * @param string $mobile 手机号
     * @return bool
     */
    public function upgrade()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $userCouponId = $this->request->param('user_coupon_id');
            $userCoupon = $this->upgradeCoupon($userCouponId);
            $this->success(__('ok'),['msg' => '升级成功', 'user_coupon' => $userCoupon]);
        }
        $this->error(__('非法请求'));
    }


    public function index()
    {
        $user = auth_user();
        $type = $this->request->param('type', 'can_use');     // 优惠券类型：geted=已领取，can_use=可用，cannot_use=暂不可用，used=已使用，expired=已过期,invalid=已失效（包含已使用和已过期）

        $userCoupons = UserCouponModel::with('coupon')->where('user_id', $user->id);

        if (in_array($type, ['geted', 'can_use', 'cannot_use', 'used', 'expired', 'invalid'])) {
            $userCoupons = $userCoupons->{Str::camel($type)}();
        }

        $userCoupons = $userCoupons->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', $userCoupons);
    }
}
